package com.umessage.hotel.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.umessage.hotel.dao.OrderPmsMapper;
import com.umessage.hotel.domain.Addaccounting;
import com.umessage.hotel.domain.CancelBook;
import com.umessage.hotel.domain.CreatBookRq;
import com.umessage.hotel.domain.OrderInfo;
import com.umessage.hotel.domain.OrderPms;
import com.umessage.hotel.service.OrderInfoService;
import com.umessage.hotel.service.OrderPmsService;
import com.umessage.hotel.service.RoomInfoService;
import com.umessage.hotel.util.HttpRequestUtil;
import com.umessage.hotel.util.JsonListMapUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@Service("orderPmsService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class OrderPmsServiceImpl  implements OrderPmsService {
	@Value("${pms.url}")
	private  String url;
	@Autowired
	private RoomInfoService roomInfoService;
	@Autowired
	private OrderPmsMapper orderPmsMapper;
	/**
	 * 酒店确认创建订单
	 */
	@Override
	public boolean establishPmsOrder(OrderInfo orderInfo) {
		boolean run=false;
		//查询订单包括几个房间
		Integer n= orderInfo.getRoomCount();
		//获取房间类型
		String roomType =roomInfoService.getRoomTypeById(orderInfo.getRoomId());
		CreatBookRq rq= new CreatBookRq();
		
		Addaccounting addaccounting = new Addaccounting();
		SimpleDateFormat sm = new SimpleDateFormat("yyyy/MM/dd");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//1已支付 2:到店,3:担保
		Integer payStatus = orderInfo.getPayStatus();
		//入住天数
		Integer t1 = 0;
		
		// 折扣价格
		BigDecimal discountPrice =orderInfo.getDiscountPrice();
		for (int i = 0; i < n; i++) {
			rq.setPhone(orderInfo.getMobile());
			rq.setHotelId(orderInfo.getHotelId().toString());
			rq.setRoomType(roomType);
			rq.setFullName(orderInfo.getResident());
			try {
				rq.setCheckInDate(sm.format(sdf.parse(orderInfo.getCheckinTime())));
				rq.setCheckOutDate(sm.format(sdf.parse(orderInfo.getCheckoutTime())));
				t1=differentDays(sdf.parse(orderInfo.getCheckinTime()),sdf.parse(orderInfo.getCheckoutTime()));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			String orderId = creatBookRq(rq,orderInfo);
			
			if("".equals(orderId)){
				
			}else{
				run= true;
				if(payStatus==1){
					//天数
					BigDecimal tianshu=new BigDecimal(t1);
					addaccounting.setHotelId(orderInfo.getHotelId().toString());
					addaccounting.setOrderId(orderId);
					addaccounting.setPcCode("S");
					//
					BigDecimal s1=discountPrice.multiply(tianshu);
					addaccounting.setAmount(s1.toString());
					addaccounting(addaccounting);
				}else if(payStatus==3){
					addaccounting.setHotelId(orderInfo.getHotelId().toString());
					addaccounting.setOrderId(orderId);
					addaccounting.setPcCode("S");
					addaccounting.setAmount(discountPrice.toString());
					addaccounting(addaccounting);
				}
			}
			
		}
		return run;
	}
	/**
	 * <pre>creatBookRq(创建pms预订单)   
	 * 创建人：MaQiang   
	 * 创建时间：2018年10月22日 下午1:53:57    
	 * 修改人：MaQiang  
	 * 修改时间：2018年10月22日 下午1:53:57    
	 * 修改备注： 
	 * @param bookRq
	 * @param orderInfo
	 * @return</pre>
	 */
	public String creatBookRq(CreatBookRq bookRq,OrderInfo orderInfo) {
		String res=null;
		try {
			res= HttpRequestUtil.pmsKingCloud("creatBookRq",JsonListMapUtil.toJSONString(bookRq),url);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("pms服务器异常");
		}
		JSONObject json = JSONObject.parseObject(res);
		String run="";
		try {
			System.out.println("创建预订单"+res);
	        String resultCode = json.getString("status");
	        SimpleDateFormat sm = new SimpleDateFormat("yyyy/MM/dd HH:mm");
	        if (resultCode != null && "1".equals(resultCode)) {
	        	Object objectNew = json.get("data");
	        	JSONArray itemList = (JSONArray) objectNew;
	        	if (itemList != null && itemList.size() > 0) {
	                for (int i = 0; i < itemList.size(); i++) {
	                	JSONObject tmp = itemList.getJSONObject(i);
	                		OrderPms orderPms =new OrderPms();
	                		orderPms.setHotelId(orderInfo.getHotelId().toString());
	                		orderPms.setOrderId(orderInfo.getOrderId());
	                		orderPms.setMemberId(orderInfo.getMemberId());
	                		run=tmp.getString("orderNum");
	                		orderPms.setPmsorderId(tmp.getString("orderNum"));
	                		orderPms.setCheckinDate(tmp.getString("checkInDate"));
	                		orderPms.setCheckoutDate(tmp.getString("checkOutDate"));
	                		orderPms.setRoomNo(tmp.getString("roomNum"));
	                		orderPms.setRoomType(tmp.getString("roomType"));
	                		orderPms.setFname(orderInfo.getResident());
	                		orderPms.setCreateTime(sm.format(new Date()));
	                		orderPms.setIscheckout("0");
	                		orderPms.setIsrefund("0");
	                		orderPmsMapper.insert(orderPms);
	                }
	            }
			}
	        
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("pms服务器异常");
		}  
		return run;
	}
	/**
	 * 添加账务
	 */
	public boolean addaccounting(Addaccounting accounting) {
		String res=null;
		boolean retur=false;
		try {
		    res= HttpRequestUtil.pmsKingCloud("addaccounting",JsonListMapUtil.toJSONString(accounting),url);
		} catch(Exception e){
			e.printStackTrace();
		}
		JSONObject json = JSONObject.parseObject(res);
		try {
			System.out.println("添加账务"+res);
	        String resultCode = json.getString("status");
	        if (resultCode != null && "1".equals(resultCode)) {
	        	retur=true;
	        }
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return retur;
	}
	/**
	 * 取消订单
	 */
	public boolean cancelbook(CancelBook accounting) {
		String res=null;
		boolean retur=false;
		try {
		    res= HttpRequestUtil.pmsKingCloud("cancelbook",JsonListMapUtil.toJSONString(accounting),url);
		} catch(Exception e){
			e.printStackTrace();
		}
		JSONObject json = JSONObject.parseObject(res);
		try {
			System.out.println("取消PMS订单"+res);
	        String resultCode = json.getString("status");
	        if (resultCode != null && "1".equals(resultCode)) {
	        	retur=true;
	        }
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return retur;
	}
	/**
	 * <pre>differentDays(计算2个时间差多少天)   
	 * 创建人：MaQiang   
	 * 创建时间：2018年10月25日 下午4:07:55    
	 * 修改人：MaQiang  
	 * 修改时间：2018年10月25日 下午4:07:55    
	 * 修改备注： 
	 * @param date1
	 * @param date2
	 * @return</pre>
	 */
	 public static int differentDays(Date date1,Date date2)
	    {
	        Calendar cal1 = Calendar.getInstance();
	        cal1.setTime(date1);
	        
	        Calendar cal2 = Calendar.getInstance();
	        cal2.setTime(date2);
	       int day1= cal1.get(Calendar.DAY_OF_YEAR);
	        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
	        
	        int year1 = cal1.get(Calendar.YEAR);
	        int year2 = cal2.get(Calendar.YEAR);
	        if(year1 != year2)   //同一年
	        {
	            int timeDistance = 0 ;
	            for(int i = year1 ; i < year2 ; i ++)
	            {
	                if(i%4==0 && i%100!=0 || i%400==0)    //闰年            
	                {
	                    timeDistance += 366;
	                }
	                else    //不是闰年
	                {
	                    timeDistance += 365;
	                }
	            }
	            
	            return timeDistance + (day2-day1) ;
	        }
	        else    //不同年
	        {
	            System.out.println("判断day2 - day1 : " + (day2-day1));
	            return day2-day1;
	        }
	    }
	@Override
	public OrderPms getorderPmsByorderpmsAndHotelId(String hotelId, String orderId) {
		return orderPmsMapper.getorderPmsByorderpmsAndHotelId(hotelId,orderId);
	}
	@Override
	public void update(OrderPms orderPms) {
		 orderPmsMapper.updateByPrimaryKey(orderPms);
		
	}
	@Override
	public List<OrderPms> getrderListOrderPms(String hotelId, String order) {
		return orderPmsMapper.getrderListOrderPms(hotelId,order);
	}
	/**
	 * <pre>cancelbookPmsOrder(通过小程序对象取消对应pms预订单)   
	 * 创建人：MaQiang   
	 * 创建时间：2018年10月22日 下午1:53:57    
	 * 修改人：MaQiang  
	 * 修改时间：2018年10月22日 下午1:53:57    
	 * 修改备注： 
	 * @param orderInfo
	 * @return</pre>
	 */
	@Override
	public void cancelbookPmsOrder(OrderInfo orderInfo) {
		
		List<OrderPms> list = getrderListOrderPms(orderInfo.getHotelId().toString(),orderInfo.getOrderId());
		CancelBook book= new CancelBook();
		for (int i = 0; i < list.size(); i++) {
			book.setHotelId(list.get(i).getHotelId());
			book.setOrderId(list.get(i).getPmsorderId());
				if(cancelbook(book)){
					list.get(i).setIscheckout("2");
					orderPmsMapper.updateByPrimaryKeySelective(list.get(i));
				}
			}
		
	}
	 

/*	 public static void main(String[] args) {
		 OrderInfo orderInfo = orderService.selectByKey(orderId);
	
	}*/
}
